<?php

class Crypto
{
    const SECRET_KEY = 'l!coAO9)*fn$9g7_+EW74WGLJls3z';
    const CYPHER = MCRYPT_RIJNDAEL_128;
    const MODE = MCRYPT_MODE_ECB;
    
    const FLASH_SECRET_KEY = "xme938AM";
    const FLASH_CYPHER = MCRYPT_DES;
    const FLASH_MODE = MCRYPT_MODE_ECB;

    public static function crypt($text, $base64 = true, $secretKey = self::SECRET_KEY)
    {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(self::CYPHER, self::MODE), MCRYPT_RAND);
        $text = mcrypt_encrypt(self::CYPHER, $secretKey, $text, self::MODE, $iv);
        return $base64 ? base64_encode($text) : $text;
    }

    public static function decrypt($text, $base64 = true, $secretKey = self::SECRET_KEY)
    {
        $iv = mcrypt_create_iv(mcrypt_get_iv_size(self::CYPHER, self::MODE), MCRYPT_RAND);
        $text = $base64 ? base64_decode($text) : $text;
        return str_replace("\x0", '', mcrypt_decrypt(self::CYPHER, $secretKey, $text, self::MODE, $iv));
    }

    public static function getIpHash($ip)
    {
        $salt = 'N3v3rG0nNaG1v3youUp';
        return substr(md5($ip . $salt), -8);
    }
}

class Common
{
    public static function getRealIp()
    {
        return isset($_SERVER['HTTP_X_REAL_IP']) ? $_SERVER['HTTP_X_REAL_IP'] : $_SERVER['REMOTE_ADDR'];
    }
    
    public static function p($name, $default = null)
    {
        if (isset($_REQUEST[$name])) {
            return $_REQUEST[$name];
        }
        
        return $default;
    }

    public  static function checkLogin($user)
    {
        try {
            if (!$user->getId()) {
                throw new Exception('<div class="center">Для просмотра страницы нужно залогиниться на <a target=_blank href="http://www.fotostrana.ru">фотостране!</div');
            } else {
                return true;
            }
        } catch (Exception $e) {
            print $e->getMessage();
            exit();
        }
    }
}

class FS
{
    public static function getUserInfo($userId, $hash)
    {
        $userId = Crypto::decrypt($userId);
        $user = json_decode($_COOKIE['user']);

        if ($hash == 'false' && $_COOKIE['user']) {
            setcookie('user', '', (time()- 3600));
            return '';
        } elseif ($hash == 'false') {
           return 'no_user';
        }

        if (isset($_COOKIE['user']) && Crypto::crypt($_COOKIE['user']) == $_COOKIE['huser'] && $user->user_id == $userId) {
            return $user;
        } else {
            return self::getUsersInfo(array($userId));
        }
    }

    public static function getUsersInfo(array $usersIds)
    {

        $json = file_get_contents('http://stage.fotostrana.ru/userinfo/api/getUser/?skey=5007d0ded168e&userIds='.implode(',', $usersIds));
        if ($json) {
            $jsonUser = json_decode($json);
            $json = json_encode($jsonUser->$usersIds[0]);
            setcookie('user', $json);
            setcookie('huser', Crypto::crypt($json));
            return '';//$json;
        }

        return array();
    }
}

class Events
{
    protected $db;
    protected $table = 'event';
    protected $photoTable = 'photos';
    protected $photoLimit = 10;
    protected $hotSeconds = 7776000; // 3 месяца
    protected $errors = array();
    protected $user = null;

    public function __construct()
    {
        $this->user = new User(json_decode($_COOKIE['user']));
        $this->db = Context::get('db');
    }

    public function incrementRocationCountEvent($idEvent)
    {
        return $this->db->prepare('UPDATE ' . $this->table . ' SET `event_count_rotate` = `event_count_rotate` + 1 WHERE `event_id` = ?')
            ->execute(array(
            $idEvent,
        ));

    }

    public function addEventAction()
    {
        if (Common::p('submit')) {

            if($this->validateAddForm()){
                $this->addEventModel(Common::p('event_name'),
                    Common::p('event_desc'),
                    !empty($_FILES['photos']['name'][0]) ? $_FILES['photos'] : array(),
                    Common::p('event_folder'),
                    Common::p('event_rotate'),
                    Common::p('event_author'),
                    Common::p('event_date'));

                    header('Location: /tv/all_events.php');
            }
        }
    }

    public function editEventAction()
    {
        if (Common::p('delete') &&
            Common::p('event_id')) {

            $this->deleteEventsByIds(array(Common::p('event_id')));
            header('Location: /tv/all_events.php');
        } else if (Common::p('submit')) {
            
            if (Common::p('event_id') &&
                Common::p('event_name') &&
                Common::p('event_date')) {   
                $this->editEventModel(Common::p('event_id'),
                    Common::p('event_name'),
                    Common::p('event_desc'),
                    !empty($_FILES['photos']['name'][0]) ? $_FILES['photos'] : array(),
                    Common::p('event_folder'),
                    Common::p('event_rotate'),
                    Common::p('event_author'),
                    Common::p('event_date'));
                    
                    header('Location: /tv/all_events.php');
                }
            } else if (Common::p('id')) {
            return $this->getEvent(Common::p('id'));
        }
    }
    
    public function addEventModel($name, $desc, $files, $folder, $rotate, $author, $date)
    {
        try {
            if ($files || $folder) {
                $eventFolder = $files ? $date . ' ' . date('H-i-s') . '-' . self::translitIt($name) : $folder;
                $this->db->prepare('INSERT INTO '.$this->table.' (event_name, event_desc, event_inserted, event_folder, event_rotate, event_author, event_date) VALUES (?, ?, ?, ?, ?, ?, ?)')
    ->execute(array(
                    $name,
                    $desc,
                    date('Y-m-d H:i:s'),
                    $eventFolder,
                    (int)(bool)$rotate,
                    $author,
                    $date,
                ));
                
                $eventId = $this->db->lastInsertId();

                if($folder) {
                   $this->addPhotosToDb($folder, $date, (int)(bool)$rotate, $eventId );           // добавить записи если выбран альбом
                }
                
                if ($files) {
                    $this->uploadImagesToStorage($files, $eventFolder);  // загрузить в папку
                    if(sizeof($files['name']) == 1){
                        $this->addPhotoToDb($files, $eventFolder, $date, (int)(bool)$rotate , $eventId);
                    } else {
                        $this->addPhotosToDb($eventFolder, $date, (int)(bool)$rotate, $eventId );
                    }
                }
                LogActionsUser::log($this->user->getId(), $eventId, LogActionsUser::ADD_EVENT);
            }
        } catch (Exception $e) {
            echo $e;
        }
    }
    
    public function editEventModel($id, $name, $desc, $files, $folder, $rotate, $author , $date)
    {
        
        try {
            $this->db->prepare('UPDATE '.$this->table.' SET event_name = ?, event_desc = ?, event_folder = ?, event_rotate = ?, event_author = ? , event_date = ? WHERE event_id = ?')
                    ->execute(array(
                    $name,
                    $desc,
                    $folder,
                    (int)(bool)$rotate,
                    $author,
                    $date,
                    $id,
            ));
            LogActionsUser::log($this->user->getId(), $id, LogActionsUser::EDIT_EVENT);

            if ($files) {
                    //$this->removeStorageEventDir($eventFolder);
                    $this->uploadImagesToStorage($files, $folder);
                    if(sizeof($files['name']) == 1) {
                        $this->addPhotoToDb($files, $folder, $date , 1 ,$id);  
                    } else {
                        $this->addPhotosToDbFromFolder($files, $folder, $date, 1 , $id);
                    }      
            }
        } catch (Exception $e) {
            echo $e;
        }
    } 
    
    // -----------------  PHOTO  ----------------  //
    
    public static function translitIt($str)
    {
        $tr = array(
            "А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
            "Д"=>"D","Е"=>"E","Ж"=>"J","З"=>"Z","И"=>"I",
            "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
            "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
            "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"TS","Ч"=>"CH",
            "Ш"=>"SH","Щ"=>"SCH","Ъ"=>"","Ы"=>"YI","Ь"=>"",
            "Э"=>"E","Ю"=>"YU","Я"=>"YA","а"=>"a","б"=>"b",
            "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
            "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
            "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
            "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
            "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
            "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya"
        );
        
        return strtr($str,$tr);
    }
    
    public function getErrors()
    {
        return $this->errors;
    }
    
    public function validateAddForm()
    {
//        $name = Common::p('event_name') ;
//        $desc = Common::p('event_desc') ;
//        $date = Common::p('event_date') ;
//        $files = $_FILES['photos'];
//        $folder =  Common::p('event_folder');
//        
//        if(!$name ) {
//            $this->errors['name'] = 'Не введено Имя';
//        } if (!$desc) {
//            $this->errors['desc'] = 'Не введено Описание';
//        } if (!$date) {
//            $this->errors['date'] = 'Не введена Дата';
//        } if (!$files || !$folder) {
//            $this->errors['files'] = 'Не выбраны файлы или Папка с фото';
//        }
//        
//        if(!$this->errors){return true;} else {return false;}     
          return true;  
    }
    
    /**
    * Добавляет записи в бд об имеющихся фото в указанной папку
    * 
    * @param mixed $folder
    */
    public function addPhotosToDb($folder, $date, $rotate, $eventId)
    {       
        $photos = $this->getEventPhotosFromStorage($folder , $photosCount = 1000); 
        
        $staytment = $this->db->prepare('INSERT INTO ' . $this->photoTable . '(event_id, photo_path, photo_inserted, photo_date, photo_rotate) VALUES (:event_id, :url , :inserted, :date, :rotate)');

        // транзакция массива фоток из папки
        try {
            $this->db->beginTransaction();
        foreach ($photos as $url) {
            $staytment->bindValue(':url', $url);
            $staytment->bindValue(':event_id', $eventId);
            $staytment->bindValue(':url', $url);
            $staytment->bindValue(':inserted', date('Y-m-d H:i:s'));
            $staytment->bindValue(':date', $date);
            $staytment->bindValue(':rotate', 1);
            $staytment->execute();
        }
            $a = $this->db->commit();
        } catch (PDOException $e) {
            $this->db->rollBack();
        }
    }
    
    /**
    * Добавляет запись о загруженном фото в бд , 1 штуку
    * 
    * @param mixed $files
    * @param mixed $folder
    */
    public function addPhotoToDb($files, $folder, $date ,$rotate ,$eventId)
    {   
        $name = $this->getUniqName($files['name'][0]);    // получить уникальное имя загруженной фотки
        
        $path = 'storage' . DIRECTORY_SEPARATOR . $folder . '/' . $name ;
        
        $this->db->prepare('INSERT INTO ' . $this->photoTable . '(event_id, photo_path, photo_inserted, photo_date, photo_rotate) VALUES (?, ?, ? ,?, ?)')
        ->execute(array(
            $eventId,
            $path ,
            date('Y-m-d H:i:s'),
            $date,
            $rotate
        ));
        
    }
    
    public function addPhotosToDbFromFolder ($files, $folder, $date ,$rotate ,$eventId)
    {
        $path = array();
        
        foreach ($files['name'] as $k => $name) {
            $files['name'][$k] = $this->getUniqName($name) ;    
        };
        
        $staytment = $this->db->prepare('INSERT INTO ' . $this->photoTable . '(event_id, photo_path, photo_inserted, photo_date, photo_rotate) VALUES (:event_id, :url , :inserted, :date, :rotate)');
        
        // транзакция массива фоток из папки
        try {
            $this->db->beginTransaction();
        foreach ($files['name'] as $name) {
            $url = 'storage/' . $folder . '/' . $name;
            $staytment->bindValue(':url', $url);
            $staytment->bindValue(':event_id', $eventId);
            $staytment->bindValue(':inserted', date('Y-m-d H:i:s'));
            $staytment->bindValue(':date', $date);
            $staytment->bindValue(':rotate', 1);
            $staytment->execute();
        }
            $this->db->commit();
        } catch (PDOException $e) {
            $this->db->rollBack();
        }        
    }
    
    public function getEventPhotosFromDb($eventId)
    {   
        $count = $this->photoLimit;

        $page = $this->getCurrentPage();
        $limit = 'LIMIT ' . $count * ($page - 1) . ', ' . $count;     // pager


                 
        $photos = $this->db->query('SELECT * FROM ' . $this->photoTable . ' WHERE event_id  =' . (int)$eventId . ' ORDER by photo_path ' .  $limit )->fetchAll(PDO::FETCH_ASSOC);;

        foreach($photos as $k=>$photo) {
             if(!$this->isFileLocated($photo['photo_id'], $photo['photo_path'])) {
                unset($photos[$k]);
             }
        }
        return $photos;
    }
    
    public function getPhotoPagerHtml($eventId)
    {
        $currentPage = (int)$this->getCurrentPage();
        
        $count = $this->db->query('SELECT COUNT(*) FROM ' . $this->photoTable . ' WHERE event_id  =' . (int)$eventId )->fetchAll(PDO::FETCH_ASSOC);
        
        $pagesCount = ceil($count[0]['COUNT(*)'] / $this->photoLimit) ;
        
        $url = $_SERVER{'PHP_SELF'} . '?id=' . Common::p('id') . '&page=';
        
        $html = "<div class='pager'>";
        
        if ($currentPage > 1 ) {
            $page = $currentPage - 1 ;
            $html .=  "<a class='btn' href='" . $url . $page . "'> Назад </a>" ;  
        }
        
        
        if($currentPage >= 3) {
            $html .=  "<a class='btn' href='" . $url . 1 . "'> 1 </a>" ;
        }
        
        if ($currentPage >= 4 ) {
           $html .=  "<a class='btn btn-space' href='javascript:void(0);return:false;'>..</a>" ;    
        }
         
        for($n = 1; $n <= $pagesCount ; $n++) {
            if($n == $currentPage){
                $class = "class='btn btn-active'";
            } else {
                $class= "class='btn'";    
            }
            if(($currentPage - 1) == $n || $currentPage == $n || ($currentPage + 1 ) == $n )  {
                $html .=  '<a ' . $class . "href='" .  $url . $n . "'>" . $n . '</a>' ; 
            }
        }
        
        if (($pagesCount - 3) >= $currentPage ) {
            $html .=  "<a class='btn btn-space' href='javascript:void(0);return:false;'>..</a>" ;
        }
        
        if (($pagesCount - 2) >= $currentPage ) {
            $html .=  "<a class='btn' href='" . $url . $pagesCount  . "'>" . $pagesCount .  '</a>' ;
        }
        
        if ($currentPage < $pagesCount ) {
            $page = $currentPage + 1 ;
            $html .=  "<a class='btn' href='" . $url  . $page . "'> Вперед </a>"; 
        }
        
        $html .= '</div>';
        return $html;
        
    }
    
    public function getCurrentPage ()
    {
        if(Common::p('page') && Common::p('page') > 1) {
            $page = Common::p('page');
        } else {
            $page = 1;
        }
        return $page;
    }
    
    public function ajaxPhotoInfoEdit()
    {
        if (!Common::p('ajax')){return array('message'=>'error 2');}
        
        if (!Common::p('id')) { return array('message'=>'error 1');}
                
        $id = Common::p('id');
                
        if(Common::p('rotate')) {
            $rotate = Common::p('val'); 
                try{
                    $this->db->prepare('UPDATE ' . $this->photoTable . ' SET photo_rotate = ? WHERE photo_id = ?')
                    ->execute(array(
                        $rotate, 
                        $id 
                ));
                    
                return array('message'=>'Изменения сохранены.'); 
                     
                } catch (PDOException $e) {
                        return array('message'=>'PDO error'); 
                }
        }
        
        if(Common::p('desc')) {
            $desc = Common::p('val');    
                    
            try{
                    $this->db->prepare('UPDATE ' . $this->photoTable . ' SET photo_desc = ? WHERE photo_id = ?')
                    ->execute(array(
                        $desc, 
                        $id 
                    ));
                    
            return array('message'=>'Изменения сохранены.'); 
                     
            } catch (PDOException $e) {
                        return array('message'=>'PDO error'); 
            }
        }

        if (Common::p('attach')) {
            $idEvent = Common::p('eventId');
            try{
                $this->db->prepare('UPDATE ' . $this->photoTable . ' SET event_id = ? WHERE photo_id = ?')
                    ->execute(array(
                    $idEvent,
                    $id
                ));
                $this->movePhotoInFolderEvent($id, $idEvent);
                return array('message'=>'Изменения сохранены.');

            } catch (PDOException $e) {
                return array('message'=>'PDO error');
            }

        }
    }

    public function movePhotoInFolderEvent($idPhoto, $idEvent)
    {
        $event = $this->getEvent($idEvent);
        $photo = $this->getPhoto($idPhoto);
        $picePathPhoto = explode('/', $photo['photo_path']);
        $folderPhoto =  $picePathPhoto[1];
        $photoName = end($picePathPhoto);
        $pathEvent = 'storage/' . $event['event_folder'] . '/' . $photoName;
        $this->deletePhotoFromAnotherFolders($photoName, $folderPhoto, $event['event_folder']);

        if ($event) {
            if (copy($photo['photo_path'], $pathEvent)) {
                return true;
            }   else {
                return false;
            }
        }
    }
    /*
     * удаляем файл изо всех папок, кроме $eventFolder и  $albumFolder
     */
    public function deletePhotoFromAnotherFolders($photoName, $albumFolder, $eventFolder = '')
    {
        $pathes = glob('storage/*/' . $photoName, GLOB_BRACE);

        foreach ($pathes as $path) {
            $picePath = explode('/', $path);
            $folder = $picePath[1];

            if ($folder != $albumFolder && $folder != $eventFolder) {
                $this->deletePhotoFromFolder($path);
            }
        }

    }

    public function getPhoto($idPhoto)
    {
        return reset($this->db->query('SELECT * FROM '. $this->photoTable . ' WHERE photo_id = ' . $idPhoto)->fetchAll());
    }
    
    public function ajaxPhotoDelete()
    {
        if (common::p('ajax') && common::p('id') && common::p('path')){
            $id = (int)common::p('id');
            $res = $this->db->query('DELETE FROM '.$this->photoTable.' WHERE photo_id =' . $id );
            if($res) {  
                if($this->deletePhotoFromFolder(common::p('path'))) {
                   return array('message'=>'Фотография удалена'); 
                } else {
                    return array('message'=>'Не удалось удалить файл из папки'); 
                } 
            } else {
                return array('message'=>'error');  
            }
        } else {
            return array('message'=>'error'); 
        } 
    }
    
    public function deletePhotoFromFolder($path)
    {   
        $path = explode('/',$path);
        return $deleteFromFolder = unlink($_SERVER['DOCUMENT_ROOT'] . '/' .  $path[0] . '/' . $path[1] . '/' . $path[2]);
    }
    
    public function isFileLocated ($id , $path)
    {
        $path = explode('/',$path);

        if(!file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $path[0] . '/' . $path[1] . '/' . $path[2])) {
            //$res = $this->db->query('DELETE FROM '. $this->photoTable.' WHERE photo_id =' . $id );
            return false;
        } else {
            return true;
        }   
    }
    
    /**
    * Сделано для ротации картинок в зависимости от свежести события
    * 
    * @param mixed $eventIds
    */
    public function hotAndCold($eventIds)
    {   

        if (sizeof($eventIds) == 1 ) {
            return implode('', $eventIds) ;  // ключи могут быть любыми, поэтому костыль с implode
        }

        $timestamp = time() - $this->hotSeconds;
        $hotDate = date('Y-m-d H:i:s', $timestamp);
        
        $idsString = implode(',',$eventIds);

        $row = $this->db->query('SELECT event_id FROM ' . $this->table . ' WHERE event_id IN ('  . $idsString  . ") and  event_rotate = 1 and event_date > '" . $hotDate . "'" );

        if ($row) {
            $hot = $row->fetchAll(PDO::FETCH_ASSOC);
        }
        $row = $this->db->query('SELECT event_id FROM ' . $this->table . ' WHERE event_id IN ('  .  $idsString  .  ") and event_rotate = 1 and event_date < '" . $hotDate . "'" );

        if ($row) {
            $cold = $row->fetchAll(PDO::FETCH_ASSOC);
        }


        $hotSize = sizeof($hot);
        $coldSize = sizeof($cold);


        // шанс на удаление в соотв. с теорией вероятности
        if ($hotSize == 1 and $coldSize == 1 and  $hotSize >= $coldSize) {
            if(mt_rand(1,100) < 40) {
                unset($cold);
            }   
        } else if ($hotSize > 1 and $coldSize >= 1 and  $hotSize >= $coldSize) {
            if(mt_rand(1,100) < 30) {
                unset($cold);    
            }
        } else if($hotSize > 1 and $coldSize > 1 and $hotSize < $coldSize) {
            if(mt_rand(1,100) < 30) {
                unset($hot);    
            }    
        }

        $eventId = Common::p('eventId');
        
        // если нет id вернуть себя
        if(!$eventIds && $eventId != 1) {
            return $eventId ; 
        }
        
        
        if(!$hot && $cold) {
            return $this->getRotateEventId($cold);
        }
        
        if($hot && !$cold) {
            return $this->getRotateEventId($hot);
        }
        
        if(!$hot && !$cold) {
            return false; 
            
        } else {

            if($eventId == 1){
                $isHot = false;
            } else {
                $isHot = $this->db->query('SELECT event_id FROM ' . $this->table . " WHERE event_id = " . $eventId  . " and event_rotate = 1 and event_date > '" . $hotDate . "'" )->fetchAll(PDO::FETCH_ASSOC);    
            }

            if($isHot) {
                return $this->getRotateEventId($cold);
            } else {
                return $this->getRotateEventId($hot);
            }      
        }  
        
    }

    /**
     * @param $events
     * При выборе события, учитываем параметр event_count_rotate - число показов события
     */
    public function getRotateEventId($events)
    {
        if (count($events) > 1) {
            //ищем event с максимальным числом показов и удаляем
            foreach($events as $key => $event) {
                if (!isset($maxCount)) {
                    $maxCount = $event['event_count_rotate'];
                }

                if ($maxCount < $event['event_count_rotate']) {
                    $maxCount = $event['event_count_rotate'];
                    $keyEvent = $key;
                }
            }
            unset($events[$keyEvent]);
        }

        $countEvent = count($events);

        $rand = mt_rand(0, $countEvent-1);
        return  $events[$rand]['event_id'];
        return  $events[$rand]['event_id'];
    }
    
    public function getAllPhoto($eventId = 1)
    {
        $events = $this->db->query('SELECT event_id, event_name, event_desc , event_rotate, event_date, event_author FROM ' . $this->table . ' WHERE event_rotate = 1 ORDER by event_date ')->fetchAll(PDO::FETCH_ASSOC);

        foreach ($events as $event) {
            if($event['event_rotate'] == 1) {
                $eventIds[] = $event['event_id'];
                $eventsArr[$event['event_id']]['event_name'] = $event['event_name'];    
                $eventsArr[$event['event_id']]['event_desc'] = $event['event_desc'];    
                $eventsArr[$event['event_id']]['event_date'] = $event['event_date'];    
                $eventsArr[$event['event_id']]['event_author'] = $event['event_author'];    
            }     
        }

        if(!$eventIds) {return false;}
        
        
        
        // провекрка есть ли в evente ротируемые фотографии
        foreach ($eventIds as $k=>$v) {
            if(!$this->db->query('SELECT event_id FROM ' . $this->photoTable . ' WHERE photo_rotate = 1 && event_id =' . $v )->fetchAll(PDO::FETCH_ASSOC)){
               unset($eventIds[$k]);
            }
        }


         
        // Убрать из массива нынешний event
        if(sizeof($eventIds) == 1 && implode('', $eventIds) == (string)$eventId){
            // от обратного , ничего не делать // то есть кроме этого eventa ничего нет , поэтому unset не надо    
        } else {
            foreach ($eventIds as $k=>$v) {
                if($v == $eventId) {
                    unset($eventIds[$k]);    
                }  
           }  
        }



        // костыль, если event вдруг удалили 
        if($eventId != 1 && !$eventIds) {
            return false;
        }

        $eventIdToQuery = $this->hotAndCold($eventIds);
        
        if(!$eventIdToQuery ) {
            return false;
        }
        
        //строка запроса
        $queryString = ' =' . $eventIdToQuery ;

        // запрос fail
        $photos = $this->db->query('SELECT * FROM ' . $this->photoTable . ' WHERE photo_rotate = 1 and event_id ' . $queryString . ' ORDER by photo_path DESC' )->fetchAll(PDO::FETCH_ASSOC);

        if(!$photos) {
            return false;
        }
         
        foreach($photos as $photo) {
            if($this->isFileLocated($photo['photo_id'], $photo['photo_path'])) {       // проверка на то есть ли в папке , если нет удалить из базы

                $arr = array();
                     
                if(!$photo['photo_name']){
                    $name = $eventsArr[$photo['event_id']]['event_name'];
                } else {
                    $name = $photo['photo_name'];
                }
                        
                if(!$photo['photo_desc']){
                    $desc = $eventsArr[$photo['event_id']]['event_desc'];
                } else {
                    $desc = $photo['photo_desc'];
                }
                
                if(!$photo['photo_date']){
                    $date = $eventsArr[$photo['event_id']]['event_date'];
                } else {
                    $date = $photo['photo_date'];
                }
                
                if(!$photo['photo_author']){
                    $author = $eventsArr[$photo['event_id']]['event_author'];
                } else {
                    $author = $photo['photo_author'];
                }
                
                $date = $this->dateFormat($date);

                $returnData[$photo['photo_id']] = array(
                            'name' => $name,
                            'desc' => $desc,
                            'url'  => $photo['photo_path'],
                            'date' => $date,
                            'author' =>$author,
                            'event_id' => $photo['event_id']
                );  
            } 
        }
               
        return $returnData;
    }
     
    //костыль для нужного формата даты
    public function dateFormat($date)
    {
        $mounths = array(
            '01' => 'Января',
            '02' => 'Февраля',
            '03' => 'Марта',
            '04' => 'Апреля',
            '05' => 'Мая',
            '06' => 'Июня',
            '07' => 'Июля',
            '08' => 'Августа',
            '09' => 'Сентября',
            '10' => 'Октября',
            '11' => 'Ноября',
            '12' => 'Декабря'
        );
        
        $formatDate = $this->deleteTimeFromDate($date);
        
        $dateFormat = explode('-', $formatDate);
        
        if (array_key_exists($dateFormat[1],$mounths)) {
            $dateFormat[1] = $mounths[$dateFormat[1]];
        }
        
        $dateFormat[0] = $dateFormat[0] . ' года.';
        
        $string = $dateFormat[2] . ' ' . $dateFormat[1] . ' ' . $dateFormat[0];
        
        return $string;
        
    }
    
    public function deleteTimeFromDate($date)
    {
        $formatDate = explode(' ', $date );
        return $formatDate[0];
    }
    
    public function getUniqName($data)
    {
        if(is_string($data)) {
            return time() . '-' . $data;  
        }
        return $data;  
    }
    
//    public function ajaxPreloadUrls() 
//    {
//        if(Common::p('counter')) {
//            $counter = Common::p('counter'); 
//            $eventId = Common::p('eventId'); 
//            
//            $returnCount = $counter + 1 ;
//            
//            $count = 10;
//            
//            $limit = ' LIMIT ' . --$counter*$count . ',' . $count;
//            
//            try{
//             
//                $select =$this->db->query('SELECT photo_path FROM '.$this->photoTable.' WHERE event_id=' . $eventId )->fetchAll(PDO::FETCH_ASSOC); 
//             
//             foreach ($select as $v) {
//                 $urls[] = $v['photo_path'];
//             }
//                    
//             return array('urls'=>$urls , 'counter'=> $returnCount); 
//                     
//             } catch (PDOException $e) {
//                return array('message'=>'PDO error'); 
//             }

//        }        
//    }
//    
    // -----------------  END PHOTO  ----------------  //
    
    public function deleteEventsByIds(array $eventsIds)
    {
        $events = $this->getEventsByIds($eventsIds);
        
        foreach ($events as $event) {
            $this->removeStorageEventDir($event['event_folder']);
        }
        
        $this->db->query('DELETE FROM '.$this->table.' WHERE event_id IN ('.implode(',', $eventsIds).')');

        foreach ($eventsIds as $eventId) {
            LogActionsUser::log($this->user->getId(), $eventId, LogActionsUser::DEL_EVENT);
        }
    }
    
    public function getEvent($eventId, $photosCount = 27)
    {
        if (!$eventId) {
            return false;
        }
        $event = array();
        $events = $this->getEventsByIds(array($eventId));
        
        if ($events) {
            $event = reset($events);
            $event['event_date'] = $this->deleteTimeFromDate($event['event_date']); 
            if ($event && $photosCount) {
                $event['photos'] = $this->getEventPhotosFromStorage($event['event_folder'], $photosCount);
            }
        }

        return $event;
    }
    
    public function getEventsByIds(array $eventsIds)
    {
        $events = array();

        if ($eventsIds) {
            $events = $this->db->query('SELECT * FROM '.$this->table.' WHERE event_id IN ('.implode(',', $eventsIds).')')->fetchAll(PDO::FETCH_ASSOC);
        }
        
        return $events;
    }
    
    public function getEventsFoldersFromDb()
    {
        $events = $this->getEvents(0, 0);
        $result = array();
        
        foreach ($events as $event) {
            $result[$event['event_folder']] = null;
        }
        
        return array_keys($result);
    }

    public function getEvents($limit = 21, $photosCount = 1, $rotated = false)
    {
        $where = '';
        
        if ($rotated) {
            $where = 'WHERE event_rotate = 1';
        }
        
        if ($limit) {
            $events = $this->db->query('SELECT * FROM '.$this->table.' '.$where.' ORDER BY event_id DESC LIMIT 0, '.(int) $limit)->fetchAll(PDO::FETCH_ASSOC);
        } else {
            $events = $this->db->query('SELECT * FROM '.$this->table.' '.$where.' ORDER BY event_id')->fetchAll(PDO::FETCH_ASSOC);
        }

        if ($photosCount) {
            $empty = array();
            
            foreach ($events as $key => $event) {
                $photos = $this->getEventPhotosFromStorage($event['event_folder'], 0);
                
                if ($photos) {
                    $events[$key]['photos'] = $photos;
                } else {
                    $empty[] = $event['event_id'];
                    unset($events[$key]);
                }
            }

            if ($empty) {
                //$this->deleteEventsByIds($empty);
            }
        }

        return $events;
    }
    
    public function getEventPhotosFromStorage($folder, $limit = 30)
    {
        $photos = glob('../storage/'.$folder.'/*.{jpg,jpeg,png,bmp,JPG,JPEG,PNG,BMP}', GLOB_BRACE);
        //usort($photos, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));
        
        if ($limit > 0) {

            foreach ($photos as $key => $photo) {
               $photos[$key] = substr($photo, 3);
            }

            $photos = array_slice($photos, 0, $limit);
        }

        return $photos;
    }
    
    public function getEventsFoldersFromStorage()
    {
        $result = array();
        $events = glob('../storage/*', GLOB_ONLYDIR);
        foreach ($events as $event) {
            $parts = explode('/', $event);
            $eventId = end($parts);
            $photos = glob($event.'/*.{jpg,jpeg,png,bmp,JPG,JPEG,PNG,BMP}', GLOB_BRACE);
            usort($photos, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));
            $result[$eventId] = reset($photos);
        }
        return $result;
    }
    
    protected function prepareImages($files)
    {
        $result = array();
        
        foreach ($files as $key => $values) {
            foreach ($values as $num => $value) {
                if ($key != 'type' || strpos($value, 'image/') === 0) {
                    $result[$num][$key] = $value;
                }
            }
        }
        
        return $result;
    }
    
    protected function removeStorageEventDir($eventFolder)
    {
//        @rmdir('../storage/'.$eventFolder.'/');
    }

    protected function uploadImagesToStorage($files, $eventFolder)
    {
        $files = $this->prepareImages($files);
        $dir = '../storage/'.$eventFolder.'/';

        if (!is_dir($dir)) {
            mkdir($dir);
        }

        
        foreach ($files as $file) {
            $fileName = $this->getUniqName($file['name']) ;
            if ($file['error'] == UPLOAD_ERR_OK) {
                move_uploaded_file($file['tmp_name'], $dir . $fileName);
            }
        }
    }
}

class User
{
    private $name;
    private $id;
    private $sex;
    private $birthday;
    private $timeOut;
    private $onlineMask;
    private $lastName;
    private $photo = array();
    private $acl;

    public function __construct($options)
    {
        if ($options) {
            $this->id         = $options->user_id;
            $this->birthday   = $options->user_birthday;
            $this->onlineMask = $options->online_mask;
            $this->timeOut    = $options->time_out;
            $this->acl        = $options->user_acl;
            $this->lastName   = $options->user_lastname;
            $this->name       = $options->user_name;
            $this->sex        = $options->user_sex;
            $this->photo['photo_url_48'] = $options->photo->photo_url_48;
            $this->photo['photo_url_97'] = $options->photo->photo_url_97;
            $this->photo['photo_url_192'] = $options->photo->photo_url_192;
        } else {
            foreach ($this as $key => $value) {
               $this->$key = '';
            }
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function getSex(){
        return $this->sex;
    }

    public function getBirthday(){
        return $this->birthday;
    }

    public function getTimeOut(){
        return $this->timeOut;
    }

    public function getOnlineMask(){
        return $this->onlineMask;
    }
    public function getLastName(){
        return $this->lastName;
    }
    public function getAcl(){
        return $this->acl;
    }

    public function getPhoto($size = 97) {

        if (!array_key_exists('photo_url_' . $size, $this->photo)) {
           return false;
        }

        return $this->photo['photo_url_' . $size];
    }

}

class LogActionsUser
{
    const ADD_EVENT   = 1;
    const DEL_EVENT   = 2;
    const EDIT_EVENT  = 3;
    const STOP_EVENT  = 4;
    const START_EVENT = 5;

    const ADD_ALBUM   = 101;
    const DEL_ALBUM   = 102;
    const EDIT_ALBUM  = 103;

    static $tableLog = 'log_action';

    protected $descriptionCode = array(
        self::ADD_EVENT   => 'Добавил событие',
        self::DEL_EVENT   => 'Удалил событие',
        self::EDIT_EVENT  => 'Отредактировал событие',
        self::STOP_EVENT  => 'Остановил событие',
        self::START_EVENT => 'Запустил событие'
    );

    protected $actionsEvents = array(
        self::ADD_EVENT,
        self::DEL_EVENT,
        self::EDIT_EVENT,
        self::STOP_EVENT,
        self::START_EVENT,
    );

    public static function log($idUser, $idContent, $contentCode, $moreOptional = null)
    {
        $db = Context::get('db');

        $db->prepare('INSERT INTO ' . self::$tableLog . ' (user_id, content_id, date, action_code, more_optional) VALUES (?, ?, ? ,?, ?)')
            ->execute(array(
            $idUser,
            $idContent ,
            date('Y-m-d H:i:s'),
            $contentCode,
            $moreOptional
        ));

    }

    /**
    * @params array $params - ключи массива это имена полей таблицы log_actions
    */
    public static function getLog(array $params)
    {

    }
}
//CREATE TABLE IF NOT EXISTS `log_action` (
// `id_log` int(11) NOT NULL AUTO_INCREMENT,
// `user_id` int(11) NOT NULL,
// `content_id` int(11) NOT NULL,
// `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
// `action_code` int(11) NOT NULL,
// `more_optional` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
// PRIMARY KEY (`id_log`)
// )ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=28 ;
//

class Albums
{
    protected $db;
    protected $table = 'albums';
    protected $photoTable = 'photos';
    protected $user;

    public function __construct()
    {
        $this->user = new User(json_decode($_COOKIE['user']));
        $this->db = Context::get('db');
    }

    public function addAlbums()
    {
        if (Common::p('submit')) {
            $this->addAlbumModel(
                Common::p('album_name'),
                !empty($_FILES['photos']['name'][0]) ? $_FILES['photos'] : array(),
                Common::p('album_author'),
                Common::p('album_folder')
            );
            header('Location: /index.php');
        }
    }

    public function addAlbumModel($name, $photos, $author, $folder)
    {
        if ($photos || $folder) {
            $albumFolder = $photos ? date('H-i-s') . '-' . Events::translitIt($name) : $folder;
            $this->db->prepare('INSERT INTO '.$this->table.' (album_name, album_autor, album_folder, album_date) VALUES (?, ?, ?, ?)')
                ->execute(array(
                    $name,
                    $author,
                    $albumFolder,
                    date('Y-m-d H:i:s')
                ));

            $albumId = $this->db->lastInsertId();

            LogActionsUser::log($this->user->getId(), $albumId, LogActionsUser::ADD_ALBUM);

            if ($folder) {
                $filesNames = $this->getAlbumPhotosFromStorage($folder);
                $this->addPhotosToDb($filesNames, $albumId);
            }

            if ($photos) {
                $filesNames = $this->uploadImagesToStorage($photos, $albumFolder, $albumId);
                $this->addPhotosToDb($filesNames, $albumId);
            }
        }
    }

    public function getAlbumsFoldersFromDb()
    {
        $albums = $this->getAlbums(0);
        $result = array();

        foreach ($albums as $album) {
            $result[$album['album_folder']] = null;
        }

        return array_keys($result);
    }
    protected function prepareImages($files)
    {
        $result = array();

        foreach ($files as $key => $values) {
            foreach ($values as $num => $value) {
                if ($key != 'type' || strpos($value, 'image/') === 0) {
                    $result[$num][$key] = $value;
                }
            }
        }

        return $result;
    }

    protected function removeStorageAlbumDir($folder)
    {
//        @rmdir('../public/storage/'.$folder.'/');
    }

    protected function uploadImagesToStorage($files, $eventFolder, $albumId)
    {
        $files = $this->prepareImages($files);
        $dir = '../public/storage/'.$eventFolder.'/';

        if (!is_dir($dir)) {
            mkdir($dir);
        }

        $filesNames = array();
        foreach ($files as $file) {
            $fileName = $this->getUniqName($file['name']) ;
            $filesNames[] = 'storage/' .$eventFolder . '/' . $fileName;
            if ($file['error'] == UPLOAD_ERR_OK) {
                move_uploaded_file($file['tmp_name'], $dir . $fileName);
            }
        }

        return $filesNames;
    }

    public function getUniqName($data)
    {
        if(is_string($data)) {
            return time() . '-' . $data;
        }
        return $data;
    }

    public function addPhotosToDb($photos, $idAlbum) {

        $staytment = $this->db->prepare('INSERT INTO ' . $this->photoTable . '(album_id, photo_path, photo_inserted, photo_date) VALUES (:album_id, :url , :inserted, :date)');

        // транзакция массива фоток из папки
        try {
            $this->db->beginTransaction();
            foreach ($photos as $url) {
                $staytment->bindValue(':url', $url);
                $staytment->bindValue(':album_id', $idAlbum);
                $staytment->bindValue(':inserted', date('Y-m-d H:i:s'));
                $staytment->bindValue(':date', date('Y-m-d H:i:s'));
                $staytment->execute();
            }
            $a = $this->db->commit();
        } catch (PDOException $e) {
            $this->db->rollBack();
        }
    }


    public function deleteAlbumsByIds(array $ids)
    {
        return;
//        foreach ($ids as $id) {
//            $album = $this->getAlbumById($id);
//          $this->removeStorageAlbumDir($album['album_folder']);
//        }

        $this->db->query('DELETE FROM ' . $this->table . ' WHERE album_id IN ('.implode(',', $ids).')');
        $this->db->query('DELETE FROM ' . $this->photoTable . ' WHERE album_id IN ('.implode(',', $ids).')');
        foreach ($ids as $id) {
            LogActionsUser::log($this->user->getId(), $id, LogActionsUser::DEL_ALBUM);
        }
    }

    public function getAlbumById($idAlbum)
    {
        $row = $this->db->query('SELECT * FROM ' . $this->table . ' WHERE album_id=' . $idAlbum)->fetchAll(PDO::FETCH_ASSOC);
        $album = reset($row);
        $album['photos'] = $this->getAlbumPhotosFromStorage($album['album_folder']);
        return $album;
    }

    public function getAlbums($limit = 12, $photosCount = 1)
    {
        if (!$limit) {
            $queryLimit = '';
        } else {
            $queryLimit  = 'LIMIT 0, ' . $limit;
        }

        $albums = $this->db->query('SELECT * FROM '.$this->table.' ORDER BY album_id DESC ' . $queryLimit)->fetchAll(PDO::FETCH_ASSOC);

        if ($photosCount) {
            $empty = array();

            foreach ($albums as $key => $album) {
                $photos = $this->getAlbumPhotosFromStorage($album['album_folder']);
                if ($photos) {
                    $albums[$key]['photos'] = $photos;
                } else {
                    $empty[] = $album['album_id'];
                    unset($albums[$key]);
                }
            }

            if ($empty) {
               // $this->deleteAlbumsByIds($empty);
            }
        }
        return $albums;
    }

    public function getFoldersFromStorage()
    {
        $result = array();
        $events = glob('storage/*', GLOB_ONLYDIR);
        foreach ($events as $event) {
            $parts = explode('/', $event);
            $eventId = end($parts);
            $photos = glob($event.'/*.{jpg,jpeg,png,bmp,JPG,JPEG,PNG,BMP}', GLOB_BRACE);
            usort($photos, create_function('$a, $b', 'return filemtime($b) - filemtime($a);'));
            $result[$eventId] = reset($photos);
        }
        return $result;
    }

    public function getAlbumPhotosFromStorage($folder, $limit = 0)
    {
        $photos = glob('storage/'.$folder.'/*.{jpg,jpeg,png,bmp,JPG,JPEG,PNG,BMP}', GLOB_BRACE);

        if ($limit > 0) {
            $photos = array_slice($photos, 0, $limit);
        }

        return $photos;
    }

    public function editAlbumAction()
    {
        if (Common::p('delete') &&
            Common::p('album_id')) {
            $this->deleteAlbumsByIds(array(Common::p('album_id')));
            header('Location: /index.php');
        } else if (Common::p('submit')) {
            if (Common::p('album_id') &&
                Common::p('album_name') &&
                Common::p('album_date')) {

                $this->editAlbumModel(Common::p('album_id'),
                    Common::p('album_name'),
                    !empty($_FILES['photos']['name'][0]) ? $_FILES['photos'] : array(),
                    Common::p('album_autor'),
                    Common::p('album_date'),
                    Common::p('album_folder'));

                    header('Location: /index.php');
                }
            } else if (Common::p('id')) {
            return $this->getAlbumById(Common::p('id'));
        }

    }

    public function editAlbumModel($idAlbum, $albumName, $newPhotos, $author, $date, $folder)
    {
        try {
            $this->db->prepare('UPDATE '.$this->table.' SET album_name = ?, album_autor = ? , album_date = ? WHERE album_id = ?')
                ->execute(array(
                $albumName,
                $author,
                $date,
                $idAlbum,
            ));

            LogActionsUser::log($this->user->getId(), $idAlbum, LogActionsUser::EDIT_ALBUM);

            if ($newPhotos) {
                //$this->removeStorageEventDir($eventFolder);
                $this->uploadImagesToStorage($newPhotos, $folder, $idAlbum);
            }
        } catch (Exception $e) {
            echo $e;
        }
    }
    public function getAlbumPhotosFromDb($idAlbum)
    {
        $photos = $this->db->query('SELECT * FROM '.$this->photoTable .' WHERE album_id = '. $idAlbum)->fetchAll(PDO::FETCH_ASSOC);
        return $photos;
    }
}


//  CREATE TABLE IF NOT EXISTS `albums` (
//  `album_id` int(11) NOT NULL AUTO_INCREMENT,
//  `album_name` varchar(200) NOT NULL,
//  `album_autor` varchar(200) NOT NULL,
//  `album_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
//  PRIMARY KEY (`album_id`)
//) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


//class Db
//{
//    protected $db;
//    
//    public function __construct()
//    {
//        $this->db = Context::get('db');
//    }
//    
//    public function fetchAssoc($query)
//    {
//        return $this->db->query($query)->fetchAll(PDO::FETCH_ASSOC);
//    }
//    
//    public function insert($table, array $fields)
//    {
//        $fields = $this->escape($fields);
//        $names  = '`'.implode('`, `', array_keys($fields)).'`';
//        $places = implode(', ', array_fill(0, sizeof($fields), '?'));
//        
//        $this->db->prepare("INSERT INTO {$table} ({$names}) VALUES ({$places})")
//                 ->execute(array_values($fields));
//        
//        return $this->db->lastInsertId();
//    }
//    
//    public function update($table, array $fields, $where, array $places)
//    {
//        $fields = $this->escape($fields);
//        $places = $this->escape($places);
//        $sets = '';
//        
//        foreach ($fields as $name => $value) {
//            $sets .= "SET `{$name}` = ?, ";
//        }
//        
//        $sets = substr($sets, 0, -2);
//        $this->db->prepare("UPDATE `{$table}` {$sets} WHERE {$where}")
//                 ->execute(array_values(array_merge($fields + $places)));
//    }
//    
//    public function escape($fields)
//    {
//        $escaped = array();
//
//        foreach ($fields as $name => $value) {
//            $escaped[mysql_escape_string($name)] = mysql_escape_string($value);
//        }
//        
//        return $escaped;
//    }
//}
//
//class NewEvent
//{
//    protected $eventsTable = 'events';
//    protected $photosTable = 'photos';
//    
//    public function __construct()
//    {
//        $this->db = new Db();
//    }
///*
//CREATE TABLE `events` (
//`event_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//`event_date` datetime NOT NULL,
//`event_inserted` datetime NOT NULL,
//`event_name` varchar(64) NOT NULL,
//`event_description` text NOT NULL,
//`event_rotate` tinyint(1) unsigned NOT NULL,
//`event_author` int(11) unsigned NOT NULL,
//PRIMARY KEY (`event_id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//*/
//    public function addEvent(array $event, array $photos, $photosDir = null)
//    {
//        $eventId = $this->db->insert($this->eventsTable, array(
//            'event_date' => $event['event_date'],
//            'event_name' => $event['event_name'],
//            'event_info' => $event['event_info'],
//            'event_author' => $event['event_author'],
//            'event_rotate' => $event['event_rotate'],
//            'event_inserted' => date('Y-m-d H:i:s'),
//        ));
//        
//        if ($eventId && ($photos || $photosDir)) {
//            if ($photosDir) {
//                $photos = $this->getPhotosFromDir($photosDir);
//            } else {
//                $photos = $this->uploadPhotos($photos);
//            }
//            
//            $this->setPhotos($eventId, $photos);
//        }
//        
//        return $eventId;
//    }
//    
//    public function editEvent($eventId, array $event = array(), array $photos = array())
//    {
//        if (!empty($event)) {
//            $this->db->update($this->eventsTable, $event, 'event_id = ?', array((int) $eventId));
//        }
//        
//        if (!empty($photos)) {
//            $this->removePhotos($eventId);
//            $this->setPhotos($eventId, $photos);
//        }
//    }
//
//    public function getPhotos($eventId)
//    {
//        return $this->db->fetchAssoc('SELECT * FROM '.$this->table);
//    }
//
//    public function editPhoto($photoId, array $photo)
//    {
//
//    }
//    
//    protected function setPhotos($eventId, array $photos)
//    {
//        foreach ($photos as $photo) {
//            $this->db->insert($this->photosTable, array(
//                'event_id' => $eventId,
//                'photo_path' => $photo,
//                'photo_inserted' => date('Y-m-d H:i:s'),
//            ));
//        }
//    }
//    
//    protected function uploadPhotos($eventId, array $files)
//    {
//        $files = $this->prepareImages($files);
//        $dir = '../public/storage/'.$eventId.'/';
//        $photos = array();
//        @mkdir($dir);
//
//        foreach ($files as $file) {
//            if ($file['error'] == UPLOAD_ERR_OK) {
//                $photos[] = $dir.$file['name'];
//                move_uploaded_file($file['tmp_name'], $dir.$file['name']);
//            }
//        }
//        
//        return $photos;
//    }
//    
//    protected function getPhotosFromDir($dir)
//    {
//        return glob('../public/storage/'.$dir.'/*.{jpg,png,bmp,JPG,PNG,BMP}', GLOB_BRACE);
//    }
//    
//    protected function removePhotos($eventId)
//    {
//        
//    }
//}
//
////$event = new NewEvent();
////echo $event->addEvent(array(
////    'event_name' => 'test',
////    'event_desc' => 'test',
////    'event_inserted' => '2012-01-13',
////    'event_folder' => 'nofolder',
////    'event_rotate' => '1',
////    'event_date' => '2012-01-13',
////), array());
//
////$db = new Db();
////$db->insert('test', array('test1' => 'test1'));
//
///*
//
//CREATE TABLE `test` (
//    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//    `test1` text NOT NULL,
//    `test2` text NOT NULL,
//    PRIMARY KEY (`id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//
//CREATE TABLE `events` (
//    `event_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//    `event_date` datetime NOT NULL,
//    `event_inserted` datetime NOT NULL,
//    `event_name` varchar(64) NOT NULL,
//    `event_info` text NOT NULL,
//    `event_rotate` tinyint(1) unsigned NOT NULL,
//    `event_author` int(11) unsigned NOT NULL,
//    PRIMARY KEY (`event_id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//
//CREATE TABLE `photos` (
//    `photo_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
//    `event_id` int(11) unsigned NOT NULL,
//    `photo_path` varchar(128) NOT NULL,
//    `photo_inserted` datetime NOT NULL,
//    `photo_date` datetime NOT NULL,
//    `photo_name` varchar(64) NOT NULL,
//    `photo_info` text NOT NULL,
//    `photo_rotate` tinyint(1) unsigned NOT NULL,
//    `photo_author` int(11) unsigned NOT NULL,
//    PRIMARY KEY (`photo_id`, `event_id`)
//) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//


//
//
//
//*/

